import { request } from '@/utils/request';

const BASE_URL = 'http://127.0.0.1:8000/api/v1';

// 统一的参数验证函数
function validateParams(params, requiredFields) {
  const missingFields = requiredFields.filter(field => !params[field]);
  if (missingFields.length > 0) {
    throw new Error(`缺少必要参数: ${missingFields.join(', ')}`);
  }
}

// 统一的请求参数构建函数
function buildQueryString(params) {
  return Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
}

// 题目相关API
export const questionApi = {
  // 获取考试题目（统一接口）
  async getQuestions(params) {
    try {
      validateParams(params, ['subject', 'vehicleType', 'examType']);
      
      const queryParams = {
        examType: params.examType,
        questionCount: params.questionCount || 100
      };
      
      const queryString = buildQueryString(queryParams);
      const response = await request({
        url: `${BASE_URL}/questions/exam/${params.subject}/${params.vehicleType}?${queryString}`,
        method: 'GET'
      });
      
      // 如果response是数组，直接返回
      if (Array.isArray(response)) {
        return response;
      }
      
      // 如果response是对象，尝试获取data字段
      if (response && typeof response === 'object') {
        const questions = response.data || response.questions || response;
        if (Array.isArray(questions)) {
          return questions;
        }
      }
      
      throw new Error('获取题目失败：返回数据格式错误');
    } catch (error) {
      console.error('获取题目失败:', error);
      throw error;
    }
  },

  // 获取模拟考试题目
  async getExamQuestions(subject, vehicleType) {
    return this.getQuestions({
      subject,
      vehicleType,
      examType: 'theory',
      questionCount: 100
    });
  },

  // 获取专项训练题目
  async getSpecialTraining(subject, vehicleType) {
    return this.getQuestions({
      subject,
      vehicleType,
      examType: 'special'
    });
  },

  // 获取顺序练习题目
  async getSequenceQuestions(subject) {
    return this.getQuestions({
      subject,
      vehicleType: 'ALL',  // 顺序练习不区分车型
      examType: 'sequence'
    });
  },

  // 检查答案
  async checkAnswer(questionId, userAnswer) {
    try {
      validateParams({ questionId, userAnswer }, ['questionId', 'userAnswer']);
      
      const response = await request({
        url: `${BASE_URL}/questions/${questionId}/check`,
        method: 'POST',
        data: { user_answer: userAnswer }
      });
      
      if (!response?.data) {
        throw new Error('检查答案失败');
      }
      
      return response.data;
    } catch (error) {
      console.error('检查答案失败:', error);
      throw error;
    }
  },

  // 保存答题记录
  async saveRecord(record) {
    try {
      validateParams(record, ['subject', 'score']);
      
      const response = await request({
        url: `${BASE_URL}/questions/record`,
        method: 'POST',
        data: record
      });
      
      if (!response?.success) {
        throw new Error('保存记录失败');
      }
      
      return response;
    } catch (error) {
      console.error('保存答题记录失败:', error);
      throw error;
    }
  },

  // 获取错题列表
  async getWrongQuestions() {
    try {
      const response = await request({
        url: `${BASE_URL}/questions/wrong`,
        method: 'GET'
      });
      
      if (!response || !response.data) {
        throw new Error('获取错题列表失败');
      }
      
      return response.data;
    } catch (error) {
      console.error('获取错题列表失败:', error);
      throw error;
    }
  },

  // 获取题目详情
  async getQuestionDetail(questionId) {
    return request({
      url: `${BASE_URL}/questions/${questionId}`,
      method: 'GET'
    });
  }
};

// 用户相关API
export const userApi = {
  // 用户登录
  async login(username, password) {
    try {
      const response = await request({
        url: `${BASE_URL}/auth/login`,
        method: 'POST',
        data: {
          username,
          password
        }
      });
      
      if (!response || !response.token) {
        throw new Error('登录失败');
      }
      
      // 保存token
      uni.setStorageSync('token', response.token);
      return response;
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },

  // 获取用户信息
  async getUserInfo() {
    try {
      const response = await request({
        url: `${BASE_URL}/user/info`,
        method: 'GET'
      });
      
      if (!response || !response.data) {
        throw new Error('获取用户信息失败');
      }
      
      return response.data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  }
};

// 统计相关API
export const statisticsApi = {
  // 获取用户答题统计
  async getUserStatistics() {
    try {
      const response = await request({
        url: `${BASE_URL}/statistics/user`,
        method: 'GET'
      });
      
      if (!response || !response.data) {
        throw new Error('获取统计信息失败');
      }
      
      return response.data;
    } catch (error) {
      console.error('获取统计信息失败:', error);
      throw error;
    }
  }
}; 